package com.eastedu.superise.handler.question;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.eastedu.converter.QuestionKnowledgeConverter;
import com.eastedu.model.ktree.KnowledgeNodeDTO;
import com.eastedu.repository.ktree.mapper.KnowledgeNodeMapper;
import com.eastedu.repository.question.mapper.QuestionAssociationMapper;
import com.eastedu.repository.question.mapper.QuestionBasicInfoMapper;
import com.eastedu.repository.question.po.QuestionAssociationPO;
import com.eastedu.repository.question.po.QuestionBasicInfoPO;
import com.eastedu.superise.handler.AbstractHistoricalDataHandler;
import com.google.common.collect.Lists;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.util.List;

/**
 * @author 袁松明
 */
@Slf4j
@Service
@DS("question")
@RequiredArgsConstructor
public class QuestionUpdateKnowledgeHistoricalDataHandler extends AbstractHistoricalDataHandler<QuestionBasicInfoPO> {
    private final QuestionAssociationMapper questionAssociationMapper;
    private final QuestionBasicInfoMapper questionBasicInfoMapper;
    private final KnowledgeNodeMapper knowledgeNodeMapper;
    private final QuestionKnowledgeConverter questionKnowledgeConverter;
    private static final List<Condition> CONDITIONS;

    static {
        //知识点范围：初中物理、初中化学、高中数学、高中物理、小学语文的全部知识点
        CONDITIONS = Lists.newArrayList(
                new Condition("CZ", "WL"),
                new Condition("CZ", "HX"),
                new Condition("GZ", "SX"),
                new Condition("GZ", "WL"),
                new Condition("XX", "YW")
        );
    }


    @Override
    protected String getSql() {
        /*
           故事ID：89604
           知识点范围：初中物理、初中化学、高中数学、高中物理、小学语文的全部知识点
           **************************** 执行脚本前，先删除线上同步服务缓存 ***************************
          0                  135798077842914287
          135798077842914287 135798077843470190
          135798077843470190 135798077844009552
          135798077844009552 135798177844563364
          135798177844563364 135799077844027675
          135799077844027675 135799077844501748
          135799077844501748 135919177844967429
          135919177844967429 374151556897443840
          374151556897443840 406101405339226112
          406101405339226112 556141670534500352
          556141670534500352 649589516017410048
          649589516017410048 731561512587407360
          731561512587407360 828583735361630208
          828583735361630208 939545053697789952
          939545053697789952
         */
        return "SELECT DISTINCT basic.* FROM t_question_association kn \n" +
                "INNER JOIN t_question_basic_info basic ON basic.id = kn.question_id\n" +
                "WHERE kn.`type` = 1 AND basic.audit_state = 2 and basic.id >= 0 AND basic.id < 135798077842914287;";
    }

    @Override
    public void callback(QuestionBasicInfoPO questionBasicInfoPo) throws SQLException {
        if (!isSupports(questionBasicInfoPo)) {
            return;
        }

        List<QuestionAssociationPO> knowledgePoints =
                questionAssociationMapper.findAllByQuestionId(questionBasicInfoPo.getId());
        if (CollectionUtils.isEmpty(knowledgePoints)) {
            log.info("试题ID：{} 无知识点", questionBasicInfoPo.getId());
            return;
        }
        knowledgePoints.forEach(item -> {
            String knowledgeGuid = item.getAssociationId();
            if (StrUtil.isEmpty(knowledgeGuid)) {
                log.info("知识点ID为空，自动跳过");
                return;
            }
            KnowledgeNodeDTO dto = knowledgeNodeMapper.findByGuid(knowledgeGuid);
            if (ObjectUtil.isNull(dto)) {
                log.info("无效知识点，自动跳过");
                return;
            }
            this.questionKnowledgeConverter.update(dto, item);
            this.questionAssociationMapper.updateById(item);
        });

        // 关联表type=1，主表上type=0
        knowledgePoints.forEach(item -> {
            item.setType(0);
        });
        String knowledgeString = JSON.toJSONString(knowledgePoints);
        questionBasicInfoMapper.updateKnowledgeById(questionBasicInfoPo.getId(), knowledgeString);
    }

    private boolean isSupports(QuestionBasicInfoPO po) {
        return CONDITIONS.stream().anyMatch(condition -> StrUtil.equalsIgnoreCase(po.getStudyPeriod(), condition.getSection())
                && StrUtil.equalsIgnoreCase(po.getSubject(), condition.getSubject()));
    }

    @Data
    @AllArgsConstructor
    private static class Condition {
        private String section;
        private String subject;
    }

}
